<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useEquipmentStore, type Equipment } from '@/stores/equipment'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'

const equipmentStore = useEquipmentStore()

const searchKeyword = ref('')
const equipmentDialogVisible = ref(false)
const editMode = ref(false)
const equipmentForm = ref<Partial<Equipment>>({
  name: '',
  brand: '',
  model: '',
  categoryId: 1,
  description: '',
  specifications: '',
  dailyRentPrice: 0,
  status: 'AVAILABLE'
})

onMounted(async () => {
  try {
    await equipmentStore.fetchEquipmentList()
  } catch (error) {
    ElMessage.error('加载设备列表失败')
  }
})

const filteredEquipment = computed(() => {
  if (!searchKeyword.value.trim()) {
    return equipmentStore.equipmentList
  }
  return equipmentStore.equipmentList.filter(eq => 
    eq.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    eq.brand.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const openAddDialog = () => {
  editMode.value = false
  equipmentForm.value = {
    name: '',
    brand: '',
    model: '',
    categoryId: 1,
    description: '',
    specifications: '',
    dailyRentPrice: 0,
    status: 'AVAILABLE'
  }
  equipmentDialogVisible.value = true
}

const openEditDialog = (equipment: Equipment) => {
  editMode.value = true
  equipmentForm.value = { ...equipment }
  equipmentDialogVisible.value = true
}

const saveEquipment = async () => {
  try {
    await equipmentStore.saveEquipment(equipmentForm.value)
    ElMessage.success(editMode.value ? '设备更新成功' : '设备添加成功')
    equipmentDialogVisible.value = false
  } catch (error) {
    ElMessage.error(editMode.value ? '设备更新失败' : '设备添加失败')
  }
}

const deleteEquipment = async (equipment: Equipment) => {
  try {
    await ElMessageBox.confirm(`确认删除设备"${equipment.name}"？`, '删除确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    await equipmentStore.deleteEquipment(equipment.id)
    ElMessage.success('设备删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('设备删除失败')
    }
  }
}

const getStatusColor = (status: string) => {
  switch (status) {
    case 'AVAILABLE': return 'success'
    case 'RENTED': return 'warning'
    case 'MAINTENANCE': return 'info'
    case 'DAMAGED': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'AVAILABLE': return '可用'
    case 'RENTED': return '已租'
    case 'MAINTENANCE': return '维护中'
    case 'DAMAGED': return '损坏'
    default: return '未知'
  }
}

</script>

<template>
  <div class="equipment-management">
    <div class="page-header">
      <h1>设备管理</h1>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索设备名称或品牌"
          style="width: 300px; margin-right: 16px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon>
          添加设备
        </el-button>
      </div>
    </div>

    <el-card>
      <el-table :data="filteredEquipment" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="设备名称" width="200" />
        <el-table-column prop="brand" label="品牌" width="120" />
        <el-table-column prop="model" label="型号" width="120" />
        <el-table-column prop="dailyRentPrice" label="日租金" width="100">
          <template #default="{ row }">
            ¥{{ row.dailyRentPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ new Date(row.createdAt).toLocaleDateString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteEquipment(row)"
              :disabled="row.status === 'RENTED'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog 
      v-model="equipmentDialogVisible" 
      :title="editMode ? '编辑设备' : '添加设备'" 
      width="600px"
    >
      <el-form :model="equipmentForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称" required>
              <el-input v-model="equipmentForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌">
              <el-input v-model="equipmentForm.brand" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="型号">
              <el-input v-model="equipmentForm.model" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日租金" required>
              <el-input-number 
                v-model="equipmentForm.dailyRentPrice" 
                :min="0" 
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="设备描述">
          <el-input 
            v-model="equipmentForm.description" 
            type="textarea" 
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="设备规格">
          <el-input 
            v-model="equipmentForm.specifications" 
            type="textarea" 
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="equipmentForm.status" style="width: 100%">
            <el-option label="可用" value="AVAILABLE" />
            <el-option label="已租" value="RENTED" />
            <el-option label="维护中" value="MAINTENANCE" />
            <el-option label="损坏" value="DAMAGED" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="equipmentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEquipment" :loading="equipmentStore.loading">
            {{ editMode ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.equipment-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.stats-row, .rental-stats {
  margin-bottom: 30px;
}

.stats-card {
  text-align: left;
  transition: transform 0.2s;
}

.stats-card:hover {
  transform: translateY(-2px);
}

.stats-card :deep(.el-card__body) {
  padding: 20px;
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.stat-icon .el-icon {
  font-size: 24px;
  color: white;
}

.equipment-total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.available {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
}

.rented {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
}

.maintenance {
  background: linear-gradient(135deg, #fa8c16 0%, #ffa940 100%);
}

.pending {
  background: linear-gradient(135deg, #722ed1 0%, #9254de 100%);
}

.active {
  background: linear-gradient(135deg, #13c2c2 0%, #36cfc9 100%);
}

.completed {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
}

.revenue {
  background: linear-gradient(135deg, #f759ab 0%, #ff85c0 100%);
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}
</style>